package utils

import (
	"context"
	"github.com/qiniu/go-sdk/v7/auth"
	"github.com/qiniu/go-sdk/v7/storage"
	"mime/multipart"
	"path"
	"strings"
	"xinyu/MyLog"
	"xinyu/global"
	"xinyu/myerr"
)

func UploadFile(file multipart.File, fileSize int64) (string, int) {
	putPolicy := storage.PutPolicy{
		Scope: global.QiNiuSetting.Bucket,
	}

	mac := auth.New(global.QiNiuSetting.AccessKey, global.QiNiuSetting.SecretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{}
	err := formUploader.PutWithoutKey(context.Background(), &ret, upToken, file, fileSize, &putExtra)
	if err != nil {
		MyLog.Log.Error("上传文件失败，错误：", err)
		return "", myerr.ErrUploadFile.Code
	}
	url := global.QiNiuSetting.QiNiuServer + ret.Key
	return url, myerr.OK.Code
}

func GetFileExt(name string) string {
	return path.Ext(name)
}

func CheckContainExt(name string) bool {
	ext := GetFileExt(name)
	ext = strings.ToUpper(ext)

	for _, allowExt := range global.QiNiuSetting.UploadImageAllowExts {
		if strings.ToUpper(allowExt) == ext {
			return true
		}
	}

	return false
}
